import {listNews, addNews, updateNews, getNews, removeNews, updateSequence} from '_api/news/news'
import {_Promise} from "_libs/util";
import Vue from "vue";

export default {
  namespaced: true,
  state: {
    newsList: [],
    news: {},
  },
  mutations: {
    setNewsList(state, newsList) {
      state.newsList = newsList.filter(func => {
        if (func.typeEntity != undefined){
          func.typeName = func.typeEntity.name
        }
        return func;
      })
    },
    addNews(state, news) {
      state.newsList.unshift(news);
    },
    updateNews(state, news) {
      for (let i = 0; i < state.newsList.length; i++) {
        let existsNews = state.newsList[i];
        if (existsNews.id === news.id) {
          let keys = Object.keys(news);
          keys.forEach(key => {
            Vue.set(state.newsList[i], key, news[key])
          })
          break
        }
      }
    },
    updateSequence(state, news) {
      for (let i = 0; i < state.newsList.length; i++) {
        let existsNews = state.newsList[i];
        if (existsNews.id === news.id) {
          let keys = Object.keys(news);
          keys.forEach(key => {
            Vue.set(state.newsList[i], key, news[key])
          })
          break
        }
      }
    },
    removeNews(state, news) {
      state.newsList = state.newsList.filter(existsNews => {
        if (existsNews.id !== news.id) {
          return existsNews;
        }
      })
    },
    getNews(state, news) {
      state.news = news;
    }
  },
  actions: {
    // 获取所有新闻
    listNews({state, commit}) {
      return _Promise(listNews(), res => {
        commit('setNewsList', res.data)
      })
    },
    // 获取新闻
    getNews({state, commit}, news) {
      return _Promise(getNews(news.id), res => {
        commit('getNews', res.data)
      })
    },

    // 添加新闻
    addNews({state, commit}, news) {
      return _Promise(addNews(news), res => {
        commit('addNews', res.data)
      })
    },

    // 更新新闻
    updateNews({state, commit}, news) {
      return _Promise(updateNews(news), res => {
        commit('updateNews', res.data)
      })
    },

    // 更新新闻
    updateSequence({state, commit}, news) {
      return _Promise(updateSequence(news), res => {
        commit('updateSequence', res.data)
      })
    },

    // 删除新闻
    removeNews({state, commit}, news) {
      return _Promise(removeNews(news.id), res => {
        commit('removeNews', news)
      })
    }
  }
}
